import os
import json
from reportlab.lib.pagesizes import A4
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
from reportlab.lib import colors
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase.cidfonts import UnicodeCIDFont
from datetime import datetime

class PDFService:
    def __init__(self):
        self.styles = getSampleStyleSheet()
        self._setup_fonts()
    
    def _setup_fonts(self):
        """设置中文字体"""
        try:
            # 使用UnicodeCIDFont，这是ReportLab内置的中文字体支持
            pdfmetrics.registerFont(UnicodeCIDFont('STSong-Light'))
            self.chinese_font = 'STSong-Light'
            print("成功注册中文字体: STSong-Light")
        except Exception as e:
            print(f"中文字体注册失败: {e}")
            try:
                # 备用方案：使用其他Unicode字体
                pdfmetrics.registerFont(UnicodeCIDFont('HeiseiMin-W3'))
                self.chinese_font = 'HeiseiMin-W3'
                print("成功注册备用中文字体: HeiseiMin-W3")
            except Exception as e2:
                print(f"备用中文字体注册失败: {e2}")
                # 最后使用默认字体
                self.chinese_font = 'Helvetica'
                print("使用默认字体 Helvetica")
    
    def generate_exam_pdf(self, exam_data, output_path=None):
        """生成试卷PDF"""
        if output_path is None:
            output_path = f"exam_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf"
        
        doc = SimpleDocTemplate(output_path, pagesize=A4)
        story = []
        
        # 标题样式
        title_style = ParagraphStyle(
            'CustomTitle',
            parent=self.styles['Heading1'],
            fontSize=18,
            spaceAfter=30,
            alignment=1,  # 居中
            fontName=self.chinese_font
        )
        
        # 副标题样式
        subtitle_style = ParagraphStyle(
            'CustomSubtitle',
            parent=self.styles['Heading2'],
            fontSize=12,
            spaceAfter=20,
            alignment=1,
            fontName=self.chinese_font
        )
        
        # 正文样式
        body_style = ParagraphStyle(
            'CustomBody',
            parent=self.styles['Normal'],
            fontSize=10,
            spaceAfter=12,
            fontName=self.chinese_font
        )
        
        # 题目样式
        question_style = ParagraphStyle(
            'Question',
            parent=self.styles['Normal'],
            fontSize=11,
            spaceAfter=8,
            leftIndent=20,
            fontName=self.chinese_font
        )
        
        # 选项样式
        option_style = ParagraphStyle(
            'Option',
            parent=self.styles['Normal'],
            fontSize=10,
            spaceAfter=4,
            leftIndent=40,
            fontName=self.chinese_font
        )
        
        # 添加试卷标题
        story.append(Paragraph(exam_data.get('name', '试卷'), title_style))
        story.append(Spacer(1, 20))
        
        # 添加试卷信息
        info_data = [
            ['总分', f"{exam_data.get('totalScore', 0)}分"],
            ['时长', f"{exam_data.get('duration', 0)}分钟"],
            ['注意事项', '请仔细阅读题目，按要求作答']
        ]
        
        info_table = Table(info_data, colWidths=[2*inch, 4*inch])
        info_table.setStyle(TableStyle([
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('FONTNAME', (0, 0), (-1, -1), self.chinese_font),
            ('FONTSIZE', (0, 0), (-1, -1), 10),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 6),
        ]))
        story.append(info_table)
        story.append(Spacer(1, 30))
        
        # 添加题目
        questions = exam_data.get('questions', [])
        for i, question in enumerate(questions, 1):
            # 题目标题
            question_title = f"{i}. {self._get_question_type_name(question.get('type', ''))}（{question.get('score', 0)}分）"
            story.append(Paragraph(question_title, subtitle_style))
            
            # 题目内容
            content = question.get('content', '')
            story.append(Paragraph(content, question_style))
            
            # 如果是选择题，添加选项
            if question.get('type') == 'choice':
                options = question.get('options', [])
                for j, option in enumerate(options):
                    option_text = f"{chr(65+j)}. {option}"
                    story.append(Paragraph(option_text, option_style))
            
            story.append(Spacer(1, 15))
        
        # 生成PDF
        doc.build(story)
        return output_path
    
    def _get_question_type_name(self, question_type):
        """获取题目类型的中文名称"""
        type_map = {
            'choice': '选择题',
            'programming': '编程题',
            'analysis': '分析题',
            'fill': '填空题',
            'essay': '简答题'
        }
        return type_map.get(question_type, '题目')
    
    def generate_answer_pdf(self, exam_data, output_path=None):
        """生成答案PDF"""
        if output_path is None:
            output_path = f"answer_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf"
        
        doc = SimpleDocTemplate(output_path, pagesize=A4)
        story = []
        
        # 标题样式
        title_style = ParagraphStyle(
            'CustomTitle',
            parent=self.styles['Heading1'],
            fontSize=18,
            spaceAfter=30,
            alignment=1,
            fontName=self.chinese_font
        )
        
        # 答案样式
        answer_style = ParagraphStyle(
            'Answer',
            parent=self.styles['Normal'],
            fontSize=10,
            spaceAfter=8,
            leftIndent=20,
            fontName=self.chinese_font
        )
        
        # 解析样式
        analysis_style = ParagraphStyle(
            'Analysis',
            parent=self.styles['Normal'],
            fontSize=9,
            spaceAfter=12,
            leftIndent=40,
            fontName=self.chinese_font,
            textColor=colors.grey
        )
        
        # 添加答案标题
        story.append(Paragraph(f"{exam_data.get('name', '试卷')} - 参考答案", title_style))
        story.append(Spacer(1, 30))
        
        # 添加答案
        questions = exam_data.get('questions', [])
        for i, question in enumerate(questions, 1):
            # 题目编号和类型
            question_title = f"{i}. {self._get_question_type_name(question.get('type', ''))}"
            story.append(Paragraph(question_title, answer_style))
            
            # 答案
            answer = question.get('answer', '')
            story.append(Paragraph(f"答案：{answer}", answer_style))
            
            # 解析
            analysis = question.get('analysis', '')
            if analysis:
                story.append(Paragraph(f"解析：{analysis}", analysis_style))
            
            story.append(Spacer(1, 15))
        
        # 生成PDF
        doc.build(story)
        return output_path 